#!/bin/bash

# Little script to let me do the development locally, and treat the 
# remote machine entirely as a 'build' and 'test' platform

CUR_DIR=`pwd`
HOST="tess-oplex-990.cs.berkeley.edu"
LOCAL="$CUR_DIR/flicker/"
LOGS="$CUR_DIR/logs"
REMOTE="/root/flicker/"
OUTPUT="/dev/null"
LOCKFILE="/tmp/flicker.lock"
CLEAN=0

mkdir -p $LOGS
export AMT_PASSWORD='Te$$1234'

function print_help {
    echo >&2 "usage: $0 [-h] [-H hostname] [-q]"
    echo -e >&2 "\t-h: Print this help message"
    echo -e >&2 "\t-H: target machine. Default to 'tess-oplex-990.cs.berkeley.edu'."
    echo -e >&2 "\t    I assume you have stuff set up in your .ssh/config appropriately"
    echo -e >&2 "\t-v: Verbose operation, prints lots of garbage from serial port"
    echo -e >&2 "\t-c: Invoke 'make clean' before making PAL code"
}

while getopts chH:v option
do
    case $option in 
        h)
            print_help
            exit 0;;
        H)
            HOST=$OPTARG
            ;;
        v)
            OUTPUT="/dev/stdout"
            ;;
        c)
            CLEAN=1
            ;;
        *)
            print_help
            exit 1;;
    esac
done

function _exit_ {
    ssh $HOST rm -f $LOCKFILE
    exit $1
}

function transfer {
    # send stuff to remote dir
    echo "Transferring files ..."
    rsync -azv $LOCAL $HOST:$REMOTE &> $OUTPUT
}

function remote_make {
    # compile stuff remotely (we can't compile it here, because my 
    # local machine is a 64 bit one)
    echo "Remote compilation ..."
    ssh $HOST make -C $REMOTE/kmod/ &> $OUTPUT
    r1=$?
    if [[ $CLEAN -ne 0 ]] ; then
        ssh $HOST make -C $REMOTE/pal/ clean &> $OUTPUT
    fi
    ssh $HOST make -C $REMOTE/pal/  &> $OUTPUT
    r2=$?
    if [[ $r1 -ne 0 || $r2 -ne 0 ]] ; then
        echo "Compile Error. Exiting now ..."
        _exit_ $((r1+r2))
    fi
}

function execute {
    filename=`ls -1 $LOGS | wc -l`
    filename=$((filename/3))
    # run the actual stuff
    echo "Time for some black magic now ..."
    # Make a copy of the syslog on the remote system
    ssh $HOST "cp /var/log/syslog /tmp/syslog"
    ssh $HOST "cd $REMOTE/pal/ && ./go.sh" &> $LOGS/run-$filename.log &
    ssh_pid=$!
    script -a -c "amtterm $HOST" $LOGS/debug-$filename.log &> $OUTPUT &
    wait $ssh_pid
    killall -9 amtterm
    # Now separate the flicker logs from syslog
    ssh $HOST "cp /var/log/syslog /tmp/syslog.new"
    ssh $HOST "diff /tmp/syslog.new /tmp/syslog | tail -n +2 | cut -f 4- -d ':' | cut -c 2- > /tmp/kern.log"
    fromdos $LOGS/debug-$filename.log
    scp -q $HOST:/tmp/kern.log $LOGS/kern-$filename.log
}


# Doesn't do atomic operations, but that's good enough for development purposes
ssh $HOST ls $LOCKFILE &> /dev/null
lock_exists=$?
if [[ $lock_exists -eq 0 ]]; then
    echo "Someone else is using the machine, try again in a few minutes!"
    exit 1
fi

ssh $HOST touch $LOCKFILE
transfer
remote_make
execute
_exit_ 0

